#include "stm32f10x.h"                  // Device header

void pwm_init(void)
{
	//配置GPIO AFIO 内部时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);  
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
	
	GPIO_InitTypeDef GPIO_struct;
	GPIO_struct.GPIO_Mode  = GPIO_Mode_AF_PP;  //复用推挽输出
	GPIO_struct.GPIO_Pin   = GPIO_Pin_0;
	GPIO_struct.GPIO_Speed = GPIO_Speed_50MHz;	
	GPIO_Init(GPIOA, &GPIO_struct);
	
	//配置定时器	
	TIM_InternalClockConfig(TIM2);  //时基单元由内部时钟驱动
	
	TIM_TimeBaseInitTypeDef TIM_Timebase_initstruct;
	TIM_Timebase_initstruct.TIM_ClockDivision     = TIM_CKD_DIV1;  //时钟分频
	TIM_Timebase_initstruct.TIM_CounterMode       = TIM_CounterMode_Up;  //计数模式
	TIM_Timebase_initstruct.TIM_Period            = 100-1;  //ARR自动重装器
	TIM_Timebase_initstruct.TIM_Prescaler         = 1440-1;  //PSC预分频器
	TIM_Timebase_initstruct.TIM_RepetitionCounter = 50;  //重复计数器	
	TIM_TimeBaseInit(TIM2,&TIM_Timebase_initstruct);  //初始化时基单元
	
	TIM_OCInitTypeDef TIM_OC_initstruct;
	TIM_OCStructInit(&TIM_OC_initstruct);
	TIM_OC_initstruct.TIM_OCMode      = TIM_OCMode_PWM1;  //输出比较模式
	TIM_OC_initstruct.TIM_OCPolarity  = TIM_OCPolarity_High;  //输出比较极性
	TIM_OC_initstruct.TIM_OutputState = TIM_OutputState_Enable;  //输出使能
	TIM_OC_initstruct.TIM_Pulse       =50;  //设置CCR占空比
	
	TIM_OC1Init(TIM2,&TIM_OC_initstruct);  //初始化输出比较单元
	
	TIM_Cmd(TIM2,ENABLE);  //开启定时器
	
}

void pwm_settone(uint16_t Period)
{
	TIM_PrescalerConfig(TIM2,Period,TIM_PSCReloadMode_Immediate);
}


